import Vue from "vue"
import Vuex from 'vuex'
import router from "../router"
import { Message } from "element-ui"

import { Login } from "@/api/Login/login"

Vue.use(Vuex)

const store = new Vuex.Store({
    state:{
      adminInfo: null ||  JSON.parse(window.localStorage.getItem('adminInfo'))
    },
    mutations:{
        saveUserInfo (state, adminInfo){
          state.adminInfo = adminInfo
        }
    },
    actions:{
        async adminLogin(context,userInfo) {
            const loginRes = await Login(userInfo);
            try {
                const loginRes = await Login(userInfo);
                console.log(loginRes)
                if (loginRes && loginRes.message === 'OK') {
                   console.log(loginRes);
                   window.localStorage.setItem('adminInfo',JSON.stringify(loginRes.data))
                   context.commit('saveUserInfo', loginRes.data)
                   router.push({name:'home'})
               }
               } catch (error) {
                   if(error.response.status === 400 && error.response.data.message === 'Invalid code.'){
                       Message.error('验证码错误')
                   }else{
                       Message.error('网络异常')
                   }
               }
        }
    }
})


export default store